package com.miuugo.common.tools;

import com.miuugo.common.result.ResultResponse;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Hibernate 校验工具类
 */
public class ValidateUtils {

    private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

    public static <T> List<String> validate(T t) {
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);

        List<String> messageList = new ArrayList<>();
        for (ConstraintViolation<T> constraintViolation : constraintViolations) {
            messageList.add(constraintViolation.getMessage());
        }

        return messageList;
    }


    public static <T> ResultResponse validateAndAdvice(T t) {
        if (t == null) {
            return ResultResponse.error("param can't be null!");
        }
        List<String> validateList = validate(t);
        if (validateList != null && !validateList.isEmpty()) {
            Set<String> set = new HashSet(validateList);
            validateList = new ArrayList<>(set);
            StringBuilder sb = new StringBuilder();
            for (String message : validateList) {
                sb.append(message + " ");
            }
            return ResultResponse.error(sb.toString());
        } else {
            return null;
        }
    }

    public static <T> ResultResponse validate(T object,String msg, Class<?>... groups) {
        if (object == null) {
            return ResultResponse.bizError(msg);
        } else {
            Set<ConstraintViolation<T>> validator = factory.getValidator().validate(object, groups);
            if (validator != null && validator.iterator().hasNext()) {
                return ResultResponse.bizError(validator.iterator().next().getMessage());
            } else {
                return null;
            }
        }
    }

    public static <T> ResultResponse validate(List<T> object,String msg, Class<?>... groups) {
        if (object == null || object.isEmpty()) {
            return ResultResponse.bizError(msg);
        } else {
            for (T t : object) {
                return validate(t,msg, groups);
            }
        }
        return null;
    }
}
